package com.cash.loan.config;

import com.cash.loan.common.annotation.support.UserLoginHandlerMethodArgumentResolver;
import com.cash.loan.common.util.RedisUtil;
import com.cash.loan.core.xss.XssFilter;
import com.cash.loan.common.filter.IpDenyFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

/**
 * @author Administrator
 * @decription
 * @Date 2017-12-05 14:35
 */
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Value("${cash.swagger-open}")
    private boolean swaggerOPen;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 增加swagger的支持
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (swaggerOPen) {
            registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }

    /**
     * xssFilter注册
     */
    @Bean
    public FilterRegistrationBean xssFilterRegistration() {
        XssFilter xssFilter = new XssFilter();
        FilterRegistrationBean registration = new FilterRegistrationBean(xssFilter);
        registration.addUrlPatterns("/*");
        return registration;
    }

    /**
     * ip黑名单过滤器注册
     * @return
     */
    @Bean
    public FilterRegistrationBean ipDenyFilterRegistration() {
        IpDenyFilter ipDenyFilter = new IpDenyFilter();
        ipDenyFilter.setRedisUtil(redisUtil);
        FilterRegistrationBean registration = new FilterRegistrationBean(ipDenyFilter);
        registration.addUrlPatterns("/*");
        return registration;
    }

    /**
     * 登录校验
     * @param argumentResolvers
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new UserLoginHandlerMethodArgumentResolver());
    }

    /**
     * 跨域配置
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowedMethods("*");
    }
}
